﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Windows.Input;

using ShellAnywhere.Model;
using System.Windows.Media;
namespace ShellAnywhere.ViewModel
{
	using IActionToken = IToken<IAction>;

	public class DispatchingShellAnywhereModel : IShellAnywhereModel
	{
		#region ctors
		public DispatchingShellAnywhereModel(IShellAnywhereModel underlying)
		{
			_Dispatcher = Dispatcher.CurrentDispatcher;
			_Underlying = underlying;
			_Underlying.ActionsChanged += OnActionsChanged;
			_Underlying.OutputAppend += OnOutputAppend;
		}
		#endregion ctors

		#region props
		public HistoryMgr HistoryMgr
		{
			get { return _Underlying.HistoryMgr; }
		}
		public Posture Posture
		{
			get { return _Underlying.Posture; }
			set { _Underlying.Posture = value; }
		}
		public IActionMgr ActionMgr
		{
			get { return _Underlying.ActionMgr; }
		}
		#endregion props

		#region methods
		public void PostureChanged(Posture posture)
		{
			_Underlying.PostureChanged(posture);
		}
		public void OnStdOutReceived(string line)
		{
			_Underlying.OnStdOutReceived(line);
		}
		public void OnStdErrReceived(string line)
		{
			_Underlying.OnStdErrReceived(line);
		}

		public void Init()
		{
			_Underlying.Init();
		}
		public void End()
		{
			_Underlying.End();
		}
		private void OnActionsChanged(int current, IAction[] actions, int dot)
		{
			System.Action action = () =>
			{
				if (ActionsChanged != null)
					ActionsChanged(current, actions, dot);
			};
			_Dispatcher.BeginInvoke(DispatcherPriority.DataBind, action);
		}
		private void OnOutputAppend(Brush color, string line)
		{
			System.Action action = () =>
			{
				if (OutputAppend != null)
					OutputAppend(color, line);
			};
			_Dispatcher.BeginInvoke(DispatcherPriority.DataBind, action);
		}		
		#endregion methods

		#region events
		public event Action<int, IAction[], int> ActionsChanged;
		public event Action<Brush, string> OutputAppend;
		#endregion events

		#region fields
		private readonly IShellAnywhereModel _Underlying;
		private readonly Dispatcher _Dispatcher;
		#endregion fields
	}
}
